package com.garbuz.svnadmin
{
	import com.garbuz.svnadmin.dto.GroupTO;
	import com.garbuz.svnadmin.dto.PermissionTO;
	import com.garbuz.svnadmin.dto.ProcessTO;
	import com.garbuz.svnadmin.dto.RepoResponseTO;
	import com.garbuz.svnadmin.dto.RepoTO;
	import com.garbuz.svnadmin.dto.UserResponseTO;
	import com.garbuz.svnadmin.dto.UserTO;
	import com.garbuz.svnadmin.services.HTTPServiceBase;
	import com.garbuz.svnadmin.view.common.ExceptionAlert;

	import common.serialization.Serializer;

	import flash.display.DisplayObject;
	import flash.system.Security;
	import flash.utils.getQualifiedClassName;

	import mx.core.Application;
	import mx.utils.URLUtil;

	public class AdminApplication
	{
		static private var _instance:AdminApplication;

		static public function get instance():AdminApplication
		{
			if (!_instance)
				_instance = new AdminApplication();

			return _instance;
		}

		private var _root:Application;
		private var _currentScreen:DisplayObject;

		public function AdminApplication()
		{
		}

		public function initialize(root:Application):void
		{
			_root = root;

			Security.allowDomain("*");
			initSerializer();
			initService();
		}

		private function initService():void
		{
			var url:String = (CONFIG::serviceUrl == "") ? _root.url : CONFIG::serviceUrl;

			HTTPServiceBase.defaultURL = url.substr(0, url.lastIndexOf("/")) + "/service";

			trace("serviceUrl:", HTTPServiceBase.defaultURL);
		}

		private function initSerializer():void
		{
			Serializer.registerType(getQualifiedClassName(UserTO));
			Serializer.registerType(getQualifiedClassName(GroupTO));
			Serializer.registerType(getQualifiedClassName(RepoTO));
			Serializer.registerType(getQualifiedClassName(PermissionTO));
			Serializer.registerType(getQualifiedClassName(UserResponseTO));
			Serializer.registerType(getQualifiedClassName(RepoResponseTO));
			Serializer.registerType(getQualifiedClassName(ProcessTO));
		}

		private function onServiceError(e:Error):void
		{
			new ExceptionAlert()
					.setText(e.message)
					.show();
		}

		public function changeScreen(screen:DisplayObject):void
		{
			if (_currentScreen)
				_root.removeChild(_currentScreen);

			_currentScreen = screen;

			if (_currentScreen)
				_root.addChild(_currentScreen);
		}

		public function get svnExternalUrl():String
		{
			return CONFIG::svnExternalUrl;
		}

		public function get svnInternalUrl():String
		{
			return CONFIG::svnInternalUrl;
		}

	}
}